package com.building.controller;


import com.building.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.building.service.CaptchaService;
import com.building.response.ServerResponse;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 验证码控制器
 *
 * @author zyp
 * @version 0.0.1
 * @since 0.0.1
 */
@Controller
public class CaptchaController {

    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    /**
     * 注入验证码服务
     */
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private AdminService adminService;

    /**
     * 获取验证码图片
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping( "/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //生成4位验证码
        String verifyCode = captchaService.genCaptha(4);
        //将验证码放到HttpSession里面
        session.setAttribute("cpacha", verifyCode);
        //设置输出的内容的类型为JPEG图像
        response.setContentType("image/jpg");
        //生成验证码图片,包含3条干扰线
        BufferedImage bufferedImage = captchaService.genCapthaImageByVerifyCode(verifyCode, 0);
        //写给浏览器
        try {
            ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            //后台返回验证码图片失败
            logger.error("", e);
        }
    }

    @RequestMapping("/login")
    @ResponseBody
    public ServerResponse<Map<String,Object>> checkcode(@RequestParam("code") String code,
                                                        @RequestParam("account") String account,
                                                        @RequestParam("password") String password,
                                                        HttpSession session){
        Object cpacha = session.getAttribute("cpacha");//获取图片验证码
        String substring = cpacha.toString().substring(0, 4);//获取前四位就是现在图片中的验证码
        String s = substring.toLowerCase();//将验证码全部转为小写
        if (code.toLowerCase().equals(s)){
            return adminService.login(account,password);
        }
        return ServerResponse.createByErrorMessage("验证码输入错误");
    }
}